<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>二分搜索</title>
  </head>
  <body>
    <script>
      // 二分查找适合已经排序好的数组
      function binarySort(findkey, arr, start, end) {
        start = start || 0;
        end = end || arr.length - 1;
        if (start <= end && findkey >= arr[start] && findkey <= arr[end]) {
          if (arr[start] == findkey) {
            return start;
          }
          if (arr[end] == findkey) {
            return end;
          }
          // let mid = Math.ceil((end - start)/2) + start
          let mid = Math.ceil((end + start) / 2); //上面和下面解析之后值一样，数学转换了一下
          if (arr[mid] == findkey) {
            return mid;
          } else if (arr[mid] > findkey) {
            return binarySort(findkey, arr, start, mid - 1);
          } else {
            return binarySort(findkey, arr, mid + 1, end);
          }
        }

        return -1;
      }
      // binarySort(3, [1, 2, 3, 4, 5, 6, 7, 8, 9]);
      console.log(binarySort(3, [1, 2, 3, 4, 5, 6, 7, 8, 9]))
    </script>
  </body>
</html>
